import React from 'react';
import {
  View,
  StyleSheet,
  Text,
  TouchableWithoutFeedback,
  Platform,
  Linking,
  NativeModules,
} from 'react-native';
import PropTypes from 'prop-types';
/**
 * 用于app更新
 */
let RNAppupdate = NativeModules.RNAppupdate;
export default class AppUpdateView extends React.PureComponent {
  render() {
    let {title, desc, updateText, updateUrl} = this.props;
    title = title ? title : '有新版本拉！';
    desc = desc ? desc : '应用有更新喔，下载试试~~~';
    let sureText = updateText ? updateText : '立即更新';
    return (
      <TouchableWithoutFeedback onPress={()=> this.props.sureCallback && this.props.sureCallback()}>   
      <View style={styles.container}>
        <View style={styles.bg}>
          <Text style={styles.title}>{title}</Text>
          <View style={styles.desc_bg}>
            <Text style={styles.desc}>{desc}</Text>
          </View>

          <TouchableWithoutFeedback onPress={this._update}>
            <View style={styles.sure_bg}>
              <Text style={styles.sure_text}>{sureText}</Text>
            </View>
          </TouchableWithoutFeedback>
        </View>
      </View>
      </TouchableWithoutFeedback> 
    );
  }
  _update = () => {
    this.props.sureCallback && this.props.sureCallback();
    if (!this.props.updateUrl || this.props.updateUrl.length == 0) {
      return;
    }
    if (Platform.OS === 'ios') {
      Linking.canOpenURL(this.props.updateUrl).then(supported => {
        if (supported) {
          Linking.openURL(this.props.updateUrl);
        } else {
          console.log('不支持跳转');
        }
      });
    } else {
      RNAppupdate.downloadApk(this.props.updateUrl);
    }
  };
}
AppUpdateView.propTypes = {
  title: PropTypes.string,//标题
  desc: PropTypes.string,//描述
  updateText: PropTypes.string,//更新按钮标题
  updateUrl: PropTypes.string.isRequired,//更新下载链接
  sureCallback: PropTypes.func //点击更新的回调，用于刷新界面等逻辑
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  bg: {
    width: 280,
    height: 230,
    borderRadius: 4,
    backgroundColor: 'white',
    overflow: 'hidden',
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 18,
    color: '#333333',
    marginTop: 12,
    fontWeight: 'bold',
  },
  desc_bg: {
    marginHorizontal: 20,
    marginTop: 12,
    marginBottom: 17,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  desc: {
    fontSize: 14,
    color: '#333333',
  },
  sure_bg: {
    width: 250,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#FF303A',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 21,
  },
  sure_text: {
    fontSize: 15,
    color: '#fff',
    fontWeight: 'bold',
  },
});
